package top.pcat.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import top.pcat.GateWayMain;

@Slf4j
public class ZookeeperListener {
    private String DEVICE_PATH = "/imServer";

    public static void main(String[] args) {
        try {
            ZookeeperListener m = new ZookeeperListener();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getOneAddress() {
        String ip = "101.43.164.47";
        return ip + ":2181";
    }

    private String getAddress() {
        String ip = "101.43.164.47";
        return ip + ":2181," + ip + ":2182," + ip + ":2183";
    }

    public ZookeeperListener() throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(getOneAddress())
                .sessionTimeoutMs(20 * 1000)
                .connectionTimeoutMs(20 * 1000)
                .retryPolicy(retryPolicy)
                .build();

        client.start();

        Stat stat = client.checkExists().forPath(DEVICE_PATH);

        if (stat == null) {
            String s = client.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.PERSISTENT)
                    .forPath(DEVICE_PATH);

            System.out.println("已创建:" + s);
        } else {
            System.out.println("已存在:" + DEVICE_PATH);
        }

        TreeCache treeCache = new TreeCache(client, DEVICE_PATH);
        TreeCacheListener treeCacheListener = (client1, event) -> {
            System.out.println("----------");

            if (event.getData() != null) {
                String[] host = event.getData().getPath().split("/");
                if (host.length==3 && event.getType()== TreeCacheEvent.Type.NODE_ADDED){
                    log.info("新加入节点： "+event.getData().getPath());

                    GateWayMain.strings.add(host[2]);
                    log.info("刷新host列表"+GateWayMain.strings);

                }else if (host.length==3 && event.getType()== TreeCacheEvent.Type.NODE_REMOVED){
                    log.info("失去一个节点： "+event.getData().getPath());

                    GateWayMain.strings.remove(host[2]);
                    log.info("刷新host列表"+GateWayMain.strings);
                }
            }
            System.out.println("----------");

        };

        treeCache.getListenable().addListener(treeCacheListener);
        treeCache.start();

        synchronized (this) {
            wait();
        }
    }
}